package bold.module.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class Server {
    private static EventLoopGroup acceptorGroup;
    private static EventLoopGroup clientGroup;

    public static void main(String[] args) throws Exception {
        try {
            ChannelFuture future = init();
            log.info("netty server start");
            future.channel().closeFuture().sync();
        } finally {
            log.info("netty server close");
            acceptorGroup.shutdownGracefully();
            clientGroup.shutdownGracefully();
        }
    }

    private static ChannelFuture init() throws InterruptedException {
        acceptorGroup = new NioEventLoopGroup(1);
        clientGroup = new NioEventLoopGroup(1);
        ServerBootstrap bootstrap = new ServerBootstrap();

        ChannelFuture channelFuture = bootstrap.group(acceptorGroup, clientGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 6 * 1024)
                .option(ChannelOption.SO_RCVBUF, 6 * 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline()
                                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2))
                                .addLast(new LengthFieldPrepender(2))
                                .addLast(new ServerHandler());
                    }
                })
                .bind(8080)
                .sync();

        return channelFuture;
    }

}
